package com.csun.cmny.provider.service.impl;

import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.TurnUsersLtMapper;
import com.csun.cmny.provider.model.constant.DeviceConstant;
import com.csun.cmny.provider.model.domain.TurnUsersLt;
import com.csun.cmny.provider.model.dto.ice.TurnUsersLtDto;
import com.csun.cmny.provider.model.dto.ice.TurnUsersLtQueryDto;
import com.csun.cmny.provider.service.TurnUsersLtService;
import com.csun.cmny.provider.utils.TurnUtils;
import com.csun.cmny.util.PublicUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-07-17 17:18
 * @Description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TurnUsersLtServiceImpl extends BaseService<TurnUsersLt> implements TurnUsersLtService {

    @Resource
    private TurnUsersLtMapper turnUsersLtMapper;

    @Override
    public List<TurnUsersLt> queryListWithPage(TurnUsersLtQueryDto turnUsersLtQueryDto) {

        PageHelper.startPage(turnUsersLtQueryDto.getPageNum(), turnUsersLtQueryDto.getPageSize());

        return turnUsersLtMapper.queryListWithPage(turnUsersLtQueryDto);
    }

    @Override
    public Integer save(TurnUsersLtDto turnUsersLtDto) {

        // TODO 1.校验参数

        // 密码计算
        // 对 name:realm:password
        String str = turnUsersLtDto.getName() + ":" +
                DeviceConstant.TURN_REALM + ":" +
                turnUsersLtDto.getPassword();

        String hmackey = TurnUtils.getMD5Str(str);

        // 2.判断是否存在
        TurnUsersLt record = new TurnUsersLt();
        record.setName(turnUsersLtDto.getName());
        record.setRealm(DeviceConstant.TURN_REALM);
        record = turnUsersLtMapper.selectOne(record);

        if (PublicUtil.isNotEmpty(record)) { // 存在，更新密码
            record.setHmackey(hmackey);
            return turnUsersLtMapper.updateByPrimaryKey(record);
        } else { // 不存在，插入
            record = new TurnUsersLt();
            record.setName(turnUsersLtDto.getName());
            record.setRealm(DeviceConstant.TURN_REALM);
            record.setHmackey(hmackey);
            return turnUsersLtMapper.insertSelective(record);
        }
    }

    @Override
    public int delete(TurnUsersLt record) {

        record.setRealm(DeviceConstant.TURN_REALM);

        return super.delete(record);
    }
}
